package tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.log4j.Logger;

import com.wechat.sample.MyWechat;

public class ReadUrl {
	private static Logger logger = Logger.getLogger(ReadUrl.class);
	
	static String key="f827a04713127b7ad490ad0b13a45fca";
	static String url="http://restapi.amap.com/v3/geocode/regeo?key=#KEY#&location=#LONGITUDE#,#LATITUDE#";
	
	
	
	
	
	public static String getNameByGps(String longitude ,String latitude){
		String myUrl=url;
		myUrl=myUrl.replace("#KEY#", key);
		myUrl=myUrl.replace("#LONGITUDE#",longitude);
		myUrl=myUrl.replace("#LATITUDE#", latitude);
		String json = loadJson(myUrl);
		
//		System.out.println(json);
		Map map=null;
        try {
			map=JsonTool.json2map(json);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			System.out.println(longitude+"---"+latitude);  
			logger.info("由GPS获取地名失败！");
			return "";
		}
		
		return map.get("regeocode").toString().split(",")[0].substring(19);
	}
	
	
	/**
	 * 如果不加utf-8，jsonAction返回的数据是乱码？？
	 * @param url
	 * @return
	 */
	
	public static String loadJson (String url) {  
        StringBuilder json = new StringBuilder();  
        try {  
            URL urlObject = new URL(url);  
            URLConnection uc = urlObject.openConnection();  
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));  
            String inputLine = null;  
            while ( (inputLine = in.readLine()) != null) {  
                json.append(inputLine);  
            }  
            in.close();  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return json.toString();  
    }  
	public static void main(String[] args) throws Exception {  
		// 由经纬度获取详细地名
//		System.out.println(ReadUrl.getNameByGps("102.165", "30.71814"));
		System.out.println(ReadUrl.getNameByGps("102", "30"));
//      String url = "http://restapi.amap.com/v3/geocode/regeo?key=f827a04713127b7ad490ad0b13a45fca&location=102.165,30.71814";  
////    String url = "http://www.kuaidi100.com/query?type=yunda&postid=1201386764793";  
//      String json = loadJson(url);  
//      Map map=JsonTool.json2map(json);
//        
//      System.out.println(json); 
//      String s=map.get("regeocode").toString().split(",")[0].substring(19);
//      System.out.println(s); 
    }  

}
